package com.its.util;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置类，用于配置跨域请求的过滤器
 */
@Configuration
public class Cors {

    /**
     * 创建并注册CorsFilter实例到Spring容器中
     *
     * @return CorsFilter实例
     */
    @Bean
    public CorsFilter corsFilter() {
        // 创建基于URL路径的跨域配置源
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 注册全局跨域配置
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
    /**
     * 构建全局跨域配置对象
     *
     * @return CorsConfiguration实例
     */
    private CorsConfiguration buildConfig() {
        // 创建CorsConfiguration对象
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许所有源地址访问
        corsConfiguration.addAllowedOrigin("*");
        // 允许所有请求头
        corsConfiguration.addAllowedHeader("*");
        // 允许所有请求方法
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

}
